<?
class lego_mysql extends lego_abstract{
	public $tabs;
	public function getDir(){ return dirname(__FILE__); }
	public function init(){
		CTitle::addSection("Mysql");
		$this->tabs = new view_radio("tabs", $this->getName());
        $this->tabs->addItem("index", "таблицы", true);
		$this->tabs->addItem("databases", "базы данных");
        $table = $this->_get("table_name");
        if($table)
            $this->tabs->addItem("browse", $table, true);
            
		Output::addTemplate("standart_tabs.tpl");
	}
    
    public function error($text){
        Output::setContent($text);
        return Output::fetch("standart_tabs.tpl");
    }
	
	function action_index(){
		$tables = Database::select("show tables");
		$tables = Arr::rotate($tables);
        if(!$tables) return $this->error("Нет табиц в базе ".Database::$database_name);
		$tables = array_pop($tables);
		$out = "<h2>Список таблиц в базе данных: ".Database::$database_name.'</h2><br>';
		foreach($tables as $one){
			$out .= "<a href='?{$this->getName()}=browse&table_name={$one}'>{$one}</a><br>";
		}
        Output::setContent($out);
        return Output::fetch("standart_tabs.tpl");
	}
	
	function action_browse(){
		$table = $this->_get("table_name");
        $this->tabs->addItem("insert", "вставить");
        $primary_key = tbl_abstract::getTablePrimaryKey($table);
		$orderby = $this->_get('orderby', $primary_key ? $primary_key : tbl_abstract::getTableFirstField($table));
		$desc = $this->_get('desc', 0);
		$total_count = Database::select("select count(*) from `$table`", true);
		$sql = "select * from `$table` where 1 order by `$orderby` ".($desc?'desc':'asc');
		$t = new view_sql($sql, $total_count, 20, 'item_list', 'p', 20);
		$fields = tbl_abstract::getTableFields($table);
        $THIS = $this;
		foreach($fields as $field_name){
			$t->getArrayView()->renameCol($field_name, "<a href='{$this->uri()->put('orderby',$field_name)->put("desc", (int)!$desc)->url()}'>$field_name</a>");
		}
        if($primary_key){
		    $t->getArrayView()->addFakeCol('d', function($row)use($table, $primary_key, $THIS){
			    return "<a href='?{$THIS->getName()}=deleterow&table_name=$table&id={$row[$primary_key]}&primary_key=$primary_key' onclick='return confirm(\"Удалить?\")'><img src='i/d.png'></a>";
		    });
            $t->getArrayView()->addFakeCol('e', function($row)use($table, $primary_key, $THIS){
                return "<a href='?{$THIS->getName()}=editrow&table_name=$table&id={$row[$primary_key]}&primary_key=$primary_key'><img src='i/e.png'></a>";
            });
        }
		$out = "<h2>$table</h2><br>";
		$out .= $t->getOutput();
        Output::setContent($out);
        return Output::fetch("standart_tabs.tpl");
	}
    
    function action_sql(){
        $sql = $this->_get('sql');
        $total_count = Database::select(preg_replace("/select.+?from/i", "select count(*) from", $sql), true);
        $t = new view_sql($sql, $total_count, 20, 'item_list', 'p', 20);
        $table = Database::getTableName($sql);
        $fields = tbl_abstract::getTableFields($table); 
        $primary_key = tbl_abstract::getTablePrimaryKey($table);
        $THIS = $this;
        $t->getArrayView()->addFakeCol('d', function($row)use($table, $primary_key, $THIS){
            return "<a href='?{$THIS->getName()}=deleterow&table_name=$table&id={$row[$primary_key]}&primary_key=$primary_key'><img src='i/d.png'></a>";
        });
        $t->getArrayView()->addFakeCol('e', function($row)use($table, $primary_key, $THIS){
            return "<a href='?{$THIS->getName()}=editrow&table_name=$table&id={$row[$primary_key]}&primary_key=$primary_key'><img src='i/e.png'></a>";
        });
        $out = "<h2>$table</h2><br>";
        $out .= $t->getOutput();
        Output::setContent($out);
        return Output::fetch("standart_tabs.tpl");
    }
    
    function action_insert(){
        $table = $this->_get("table_name");
        $lego = new lego_form('insert_lego', $table);
        $lego->run();
        Output::setContent($lego->getOutput());
        return Output::fetch("standart_tabs.tpl");
    }
	
	function action_editrow(){
		$table = $this->_get("table_name");
        $id = $this->_get("id");
		$primary_key = $this->_get("primary_key");
		$f = new view_form("editrow", "?{$this->getName()}=saverow&table_name=$table&id=$id&primary_key=$primary_key");
		$f->createFromTable($table);
		$rows = Database::select("select * from `$table` where `$primary_key`='$id' limit 1");
		$f->loadFromArray($rows[0]);
		$out = "<h2><a href='?{$this->getName()}=browse&table_name=$table'>$table</a></h2>";
		$out .= $f->getOutput();
        Output::setContent($out);
        return Output::fetch("standart_tabs.tpl");
	}
	
	function action_saverow(){
		$table = $this->_get("table_name");
		$id = $this->_get("id");
        $primary_key = $this->_get("primary_key");
		$o = new tbl_abstract($id, $table, $primary_key);
		$o->loadFromArray($_POST);
		$o->update();
		return $this->action_editrow();
	}
	
	function action_deleterow(){
		$table = $this->_get("table_name");
		$id = $this->_get("id");
        $primary_key = $this->_get("primary_key");
        $o = new tbl_abstract($id, $table, $primary_key);
		$o->delete();
		$this->_goto('?'.$this->uri()->put($this->getName(), 'browse'));
	}
	
	
	function action_databases(){
		$dbs = Database::select("show databases");
		$dbs = Arr::rotate($dbs);
		$dbs = array_pop($dbs);
		$out = "<h2>Список баз данных</h2><br>";
		foreach($dbs as $one){
			$out .= "<a href='?{$this->getName()}=setdb&db={$one}' style='color:red; font-size:14px'>{$one}</a><br>";
		}
        $out .= "<br><br>";
        $out .= "<a href='?{$this->getName()}=exit'>ВЫХОД</a>";
        Output::setContent($out);
        return Output::fetch("standart_tabs.tpl");
	}
	
	function action_setdb(){
		$db = $this->_get("db");
		$_SESSION['DB_NAME'] = $db;
		$this->_goto("?");
	}
	
	function action_auth(){
		CTitle::addSection("Авторизация в БД");
		$f = new view_form('dbauth', "?{$this->getName()}=auth_submit");
		$f->addField('dbname', '', Database::$database_name);
		$f->addField('host', '', Database::$host);
		$f->addField('username', '', Database::$user_name);
		$f->addField('pass', 'password' /*, Database::$user_pass*/);
		$f->addField('', 'submit', "Войти");
		Output::setContent($f->getOutput());
        return Output::fetch("standart_tabs.tpl");
	}
	
	function action_auth_submit(){
		$_SESSION['DB_NAME'] = $this->_post('dbname');
		$_SESSION['DB_HOST'] = $this->_post('host');
		$_SESSION['DB_USERNAME'] = $this->_post('username');
		$_SESSION['DB_USERPASS'] = $this->_post('pass');
		$this->_goto("?");
	}
    
    function action_exit(){
        unset($_SESSION['DB_NAME']);
        unset($_SESSION['DB_HOST']);
        unset($_SESSION['DB_USERNAME']);
        unset($_SESSION['DB_USERPASS']);
        $this->_goto("?");
    }
	
}
?>